package com.lw.extraceim.ui.fragments;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;

import androidx.annotation.Nullable;

import com.google.gson.reflect.TypeToken;
import com.lw.extraceim.R;
import com.lw.extraceim.app.ExtraceApplication;
import com.lw.extraceim.loader.ExpressSheetLoader;
import com.lw.extraceim.model.ExpressSheet;
import com.lw.extraceim.net.HttpResponseParam;
import com.lw.extraceim.net.ResponseCode;
import com.lw.extraceim.net.callback.HttpResponseParamCallback;
import com.lw.extraceim.ui.activity.es.ExpressSheetInfoActivity;
import com.lw.extraceim.ui.adapter.ExpressSheetAdapter;
import com.lw.extraceim.ui.fragments.base.BaseFragment;
import com.lw.extraceim.util.DialogUtil;
import com.lw.extraceim.util.JsonUtils;
import com.lw.extraceim.util.ZxingUtil;
import com.lw.extraceim.zxing.ExtraceCaptureActivity;

import org.json.JSONException;

import java.util.List;
import java.util.Objects;

import okhttp3.Call;

/**
 * @Author : liwei
 * @Email : 1759840027@qq.com
 * @Description : 我的派送列表
 * @Date : 2019/5/13 21:08
 */
public class MyDispatchFragment extends TaskFragment {
    private static final String TAG = "MyDeliverFragment";

    private Button mAddDeliverEs; //添加派送快件
    private ListView mDelivingEsList;//正在派送的快件列表
    private ExpressSheetAdapter esAdapter;
    private List<ExpressSheet> esList;//快件列表

    private ExpressSheetLoader esLoader;


    public MyDispatchFragment(Context mContext, ExtraceApplication application) {
        super(mContext, application);
    }

    @Override
    public View initView() {
        View view = View.inflate(mContext, R.layout.layout_my_deliver_fragment, null);
        mAddDeliverEs = view.findViewById(R.id.add_deliver_es);
        mDelivingEsList = view.findViewById(R.id.deliving_es_list);
        return view;
    }

    @Override
    public void initData() {
        esLoader = new ExpressSheetLoader(getContext());

    }

    @Override
    public void initEvent() {
        mAddDeliverEs.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ZxingUtil.startQRScan(getActivity(), ExtraceCaptureActivity.class, "扫描快件", ExtraceCaptureActivity.SCAN_ADD_DELIVER_ES);
            }
        });

        mDelivingEsList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
                DialogUtil.showDialog(getContext(), "提示", "是否交付?", "是", "否", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        deliverEs(esList.get(position).getId());
                    }
                }, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                return false;
            }
        });
        mDelivingEsList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ExpressSheetInfoActivity.actionStart(getContext(),esList.get(position));
            }
        });
    }

    @Override
    public void refreshUI() {

    }

    /**
     * 添加派送快件
     *
     * @param esId
     */
    public void addDispatchEs(String esId) {
        //添加派送快件
        esLoader.dispatchEs(esId, application.getUserInfo().getuId(), new HttpResponseParamCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                alert("网络错误" + e);
            }

            @Override
            public void onResponse(HttpResponseParam response, int id) {
                if (response.code.getCode() == ResponseCode.SUCESS) {
                    //添加派送快件成功
                    DialogUtil.showDialog(getContext(), "提示", "添加快件成功，是否继续添加?", "是", "否", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            ZxingUtil.startQRScan(getActivity(), ExtraceCaptureActivity.class, "扫描快件", ExtraceCaptureActivity.SCAN_ADD_DELIVER_ES);
                        }
                    }, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                } else {
                    alert(response.code.getMessage());
                }
            }
        });
    }

    /**
     * 加载用户的派送列表
     */
    public void loadDelivingEsList() {
        esLoader.loadDispatchEs(application.getUserInfo().getuId(), new HttpResponseParamCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                alert("网络错误" + e);
            }

            @Override
            public void onResponse(HttpResponseParam response, int id) {
                Log.d(TAG, "onResponse: " + response.reseponseJson);
                if (response.code.getCode() == ResponseCode.SUCESS) {
                    //加载快件列表成功
                    try {
                        esList = JsonUtils.fromJson(response.reseponseJson.getJSONArray("expressSheetList").toString(), new TypeToken<List<ExpressSheet>>() {
                        });
                        for (ExpressSheet expressSheet : esList) {
                            expressSheet.onLoad();
                        }
                        refreshDelivingEsList();
                    } catch (JSONException e) {
                        e.printStackTrace();
//                        DialogUtil.alert(getContext(), "解析json失败" + e.getMessage());
                    }
                } else {
                    DialogUtil.alert(getContext(), response.code.getMessage());
                }
            }
        });
    }

    public void deliverEs(final String esId) {
        esLoader.deliverEs(esId, application.getUserInfo().getuId(), new HttpResponseParamCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                alert("网络错误" + e);
            }

            @Override
            public void onResponse(HttpResponseParam response, int id) {
                if (response.code.getCode() == ResponseCode.SUCESS) {
                    DialogUtil.alert(getContext(), "交付成功");
                    for (int i = 0; i < esList.size(); i++) {
                        if (Objects.equals(esList.get(i).getId(), esId)) {
                            esList.remove(i);
                            break;
                        }
                    }
                    refreshDelivingEsList();
                } else {
                    DialogUtil.alert(getContext(), response.code.getMessage());
                }
            }
        });
    }

    /**
     * 刷新快件列表
     */
    public void refreshDelivingEsList() {
        mDelivingEsList.setAdapter(new ExpressSheetAdapter(esList, getContext()));
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case ExtraceCaptureActivity.SCAN_ADD_DELIVER_ES: {
                String esId = ZxingUtil.scanResult(resultCode, data);//快件编号
                addDispatchEs(esId);
                break;
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.d(TAG, "onResume: 执行onResume方法");
        loadDelivingEsList();
    }
}
